/*
 * @FileName: OrganizationService.java
 * 
 * @Author
 * 
 * @Description:
 * 
 * @Date 2016年1月7日 下午2:42:39
 * 
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.model.MemberOrg;
import cn.hpclub.server.service.LoginService.VerifyEmpCode9999Exception;
import cn.hpclub.server.service.LoginService.VerifyEmpCodeException;
import cn.hpclub.server.util.DESCrypto;
import cn.hpclub.server.util.SystemConfigUtil;

/**
 * Class description goes here
 *
 * @author
 */
public class RedirectService{

    private static final Logger   logger        = LoggerFactory.getLogger(RedirectService.class);
    public static RedirectService service       = new RedirectService();

    public static final String    URL           = "url";
    public static final String    MSG           = "msg";
    private static String         PHONE         = "phone";
    private String                businessUrl   = SystemConfigUtil.getSystemConfig().getTariffBusiness();
    private static String         CODE          = "businessCode";
    private final static String[] BUSINESS_CODE = { "ACAZ25128", "ACAZ25129", "ACAZ22308", "ACAZ22309", "ACAZ22310",
            "ACAZ22311", "ACAZ23312", "ACAZ23313" };

    @SuppressWarnings("deprecation")
    public Map<String, String> getPara(String data) throws Exception{
        Map<String, String> hm = new HashMap<String, String>();
        String temp;
        String[] p = DESCrypto.decryptRedirect(URLDecoder.decode(data), ClientApiConstant.CONSTANT_DES_KEY).split("&");
        for(int i = 0; i < p.length; i++){

            temp = p[i];
            hm.put(temp.substring(0, temp.indexOf("=")), temp.substring(temp.indexOf("=") + 1));
        }
        return hm;
    }

    public String getRedirectUrl(String data) throws Exception{
        Map<String, String> p = getPara(data);
        String phoneNumber = p.get(PHONE);
        Record userInfo = getUserInfo(phoneNumber);
        Record tariffInfo = getTariffInfo(BUSINESS_CODE[Integer.parseInt(p.get(CODE)) - 1]);
        return generateBusinessUrl(phoneNumber, userInfo, tariffInfo);
    }

    /**
     * @Title: generateBusinessUrl
     * @Description:生成业务办理URL
     * @param phoneNumber业务员号码
     * @param userInfo业务员信息
     * @param tariffInfo业务信息
     * @return StringBuffer
     */

    private String generateBusinessUrl(String phoneNumber, Record userInfo, Record tariffInfo){
        StringBuffer url = new StringBuffer(businessUrl);
        url.append("?act_type=");
        url.append(tariffInfo.getInt("act_type"));
        url.append("&storeId=");
        url.append(userInfo.getInt("org_id"));
        url.append("&userId=");
        url.append(userInfo.getInt("id"));
        url.append("&EmpCode=");
        url.append(userInfo.getStr("emp_code"));
        url.append("&phonenumber=");
        url.append(phoneNumber);
        url.append("#/handle?tariff_id=");
        url.append(tariffInfo.getInt("tariff_id"));
        logger.info("redirect url=" + url);
        return url.toString();
    }

    /**
     * @Title: getTariffInfo
     * @Description:查询业务信息
     * @param p请求参数
     * @return
     * @throws IOException
     *             Record
     */

    private Record getTariffInfo(String business_code) throws IOException{
        logger.info("business_code=" + business_code);
        String sql = "SELECT act.title AS act_title, act.`type` AS act_type, tar.name AS tariff_name, tar.id AS tariff_id, tar.code AS tariff_code, tar.`type` AS tariff_type FROM tariff AS tar, tariff_class_relation AS tcr,activity_tariff_class_relation AS atcr,activity AS act where tcr.tariff_id=tar.id AND tcr.tariff_class_id=atcr.tariff_class_id AND atcr.activity_id=act.id AND tar.code=?";
        Record tariffInfo = Db.findFirst(sql, business_code);
        if(tariffInfo == null){
            throw new IOException("您要办理的套餐不存在，请检查参数");
        }
        return tariffInfo;
    }

    /**
     * @Title: getUserInfo
     * @Description:TODO
     * @param phoneNumber
     * @return
     * @throws IOException
     *             Record
     */

    private Record getUserInfo(String phoneNumber) throws IOException{
        Record record = Db.findFirst("SELECT id, emp_code, org_id FROM member_org WHERE user_name=?", phoneNumber);
        if(record == null){
            throw new IOException("该员工不存在!");
        }
        return record;
    }

    @SuppressWarnings("unused")
    private String getGroupId(Map<String, String> result, Map<String, String> p, Record record)
            throws IOException, VerifyEmpCodeException, VerifyEmpCode9999Exception{
        String group_id = new LoginService(p.get(PHONE), "", false)
                .getCityCodeIdFromRzl(p.get(PHONE), record.getStr(MemberOrg.EMP_CODE)).get("group_id");

        if(group_id == null){
            throw new IOException("员工组织ID不存在!");
        }
        return group_id;
    }
}
